package trafficAgent;

import java.util.Random;

import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.graph.SimpleDirectedWeightedGraph;

import model.Car;
import model.Config;
import model.Crossroads;
import model.GraphUtility;
import model.Street;
import jade.core.behaviours.OneShotBehaviour;

public class AddRandomCar extends OneShotBehaviour {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	TrafficAgent agent; 
	Random rand = new Random();
	
	public AddRandomCar(final TrafficAgent myAgent) {
		super(myAgent);
		agent = myAgent;
	}
	
	@Override
	public void action() {
		
		for(int i = 0; i < agent.getCarPerStep(); i++)
			if(agent.getMap().getCars().size() < Config.getMaxNumCar())
				if(!addRandomCar())
					if(agent.getMap().getCars().size() < Config.getMaxNumCar())
						i--;
		
		
		agent.addBehaviour(new MasterBehaviour(agent));
	}

	private boolean addRandomCar() {
		final SimpleDirectedWeightedGraph<Crossroads, DefaultWeightedEdge> graph = GraphUtility.genGraph(agent.getMap());	
		final DefaultWeightedEdge start = (DefaultWeightedEdge) graph.edgeSet().toArray()[rand.nextInt(graph.edgeSet().size())];
		final DefaultWeightedEdge end = (DefaultWeightedEdge) graph.edgeSet().toArray()[rand.nextInt(graph.edgeSet().size())];
		
		final Street curPos = new Street(graph.getEdgeSource(start), graph.getEdgeTarget(start));
		final int curPosIndex = 0;
		
		final Street destPos = new Street(graph.getEdgeSource(end), graph.getEdgeTarget(end));
		final int destPosIndex = 0;
		
		if(agent.getMap().freeRoad(curPos, curPosIndex)){
				agent.getMap().getCars().add(new Car(curPos, curPosIndex, destPos, destPosIndex));
				return true;
		}
		
		return false;
	}

	

}
